﻿using System;
using UnityEngine;

namespace Core
{
    public class TickItem : Core.Component
    {
        public Action<float> Func;
        public float Interval;
        public bool Breakup;
        public bool Immediate;

        private float elapsedTime;

        public void Start()
        {
            if (Immediate)
            {
                Func(0);
            }

            if (Breakup)
            {
                //第一次间隔时间，随机在[0,Interval)之间，可以将同时触发的定时器打散，防止某一帧执行压力多大
                elapsedTime = UnityEngine.Random.Range(0, Interval);
            }
            else
            {
                elapsedTime = Interval;
            }
        }

        public void Update()
        {
            elapsedTime -= Time.deltaTime;

            if (elapsedTime <= 0)
            {
                elapsedTime += Interval;
                try
                {
                    Func(Interval);
                }
                catch (Exception e)
                {
                    log.err(e);
                }
            }
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();

            Func = null;
            Interval = 0;
        }

    }
}
